<?php
namespace App\Http\Controllers;

use DateTime;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Http;
use Carbon\Carbon;


class AppController extends Controller
{

    public function getCompany(Request $request)
    {
        $res = DB::table('company')->where('status', 1)->where('deleted_at',null)->select('id', 'name as label')->get();
        return $res;
    }

    public function getTeam(Request $request)
    {
        $res = DB::table('team')->where('status', 1)->where('deleted_at',null)->select('id', 'name as label')->get();
        return $res;
    }

    public function getEngineering(Request $request)
    {
        $data = $request->all();
        $user_id = $data['user_id'];


        $user_info = DB::table('admin_users')->where('id', $user_id)->first();
        if($user_info->whole == 0){
            $res = DB::table('engineering')->where('deleted_at',null)->select('id', 'engineering_name as label')->get();
        }
        if($user_info->whole == 1){
            $res = DB::table('engineering')->where('deleted_at',null)->where('manager','like','%'.$user_id.'%')->select('id', 'engineering_name as label')->get();
        }
        if($user_info->whole == 2){
            $res = DB::table('engineering')->where('deleted_at',null)->where('manager','like','%'.$user_id.'%')->select('id', 'engineering_name as label')->get();
        }

        return $res;

    }

    public function getTypeWork(Request $request)
    {
        $res = DB::table('type_work')->select('id', 'name as label')->get();
        return $res;
    }

    function uploadImg(Request $request)
    {
        // 文件对象
        $file = $request->file('file');
        // 判断图片上传是否错误
        if (!$file->isValid()) {
            // 文件上传失败
            return $this->ErrJson("上传文件验证失败", false);
        }
        // 文件原名
        $original_name = $file->getClientOriginalName();
        // 文件扩展名(文件后缀)
        $ext = $file->getClientOriginalExtension();
        // 临时文件的绝对路径
        $real_path = $file->getRealPath();
        // 文件类型
        $type = $file->getClientMimeType();
        // 文件大小
        $size = $file->getSize();

        // 文件大小校验
        if ($size > 5 * 1024 * 1024) {
            return $this->ErrJson("文件大小超过了5M", false);
        }

        // 文件后缀校验
        $ext_arr = array('jpg', 'jpeg', 'png', 'gif');
        if (!in_array($ext, $ext_arr)) {
            return $this->ErrJson("文件格式不正确", false);
        }

        // 文件路径
        $file_dir = public_path() . "/uploads/photo";

        // 检测文件路径是否存在,不存在则创建
        if (!file_exists($file_dir)) {
            mkdir($file_dir, 0777, true);
        }

        // 文件名称
        $file_name = uniqid() . '.' . $ext;
        // 重命名保存
        $file->move($file_dir, $file_name);

        // 返回结果
        $res['res'] = '/photo/'.$file_name;
        $res['url'] = env('APP_URL').'uploads/photo/'.$file_name;
        return $this->OkJson($res);
    }


    public function addWorkUser(Request $request){
        $data = $request->all();
        unset($data['idProject']);

        if (!$this->isValidID($data['id_card'])) {
            return $this->ErrJson(102,'身份证号格式错误');
        }

        $cf = DB::table('work_user')->where('id_card',$data['id_card'])->first();
        if(!empty($cf->status == 1)){
            return $this->ErrJson(102,'该人员已在其他工程入职,在职工程为:'.$cf->engineering);
        }
        if($cf != null && $cf->misdeed != 1){
            return $this->ErrJson(102,'该人员存在不端行为,行为发生工程为:'.$cf->engineering);
        }

        if(empty($cf)){
            $data['status'] = 1;
            $data['enter_time'] = Carbon::now();
            $data['age'] = $this->getAgeByID($data['id_card']);
            $data['uploader'] = $data['user_id'];
            unset($data['user_id']);
            $res = DB::table('work_user')->insert($data);
        }else{
            $data['status'] = 1;
            $data['enter_time'] = Carbon::now();
            $data['age'] = $this->getAgeByID($data['id_card']);
            $data['uploader'] = $data['user_id'];
            unset($data['user_id']);
            DB::table('work_user')->where('id_card',$data['id_card'])->update($data);
        }

        $details = '首次入职';
        $type = 1;
        if(!empty($cf->status == 2)){
            $details = '再次入职';
            $type = 3;
        }

        $history = [];
        $history['name'] = $data['name'];
        $history['id_card'] = $data['id_card'];
        $history['engineering'] = $data['engineering'];
        $history['type'] = $type;
        $history['details'] = $details;
        $history['enter_time'] = Carbon::now();
        $history['created_at'] = Carbon::now();
        DB::table('work_user_history')->insert($history);

        return $this->OkJson('保存成功');
    }

    function isValidID($id) {
        // 验证18位身份证号码
        $pattern18 = '/^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(10|11|12))((0[1-9])|([1-2][0-9])|30|31)\d{3}(\d|X)$/i';
        // 验证15位身份证号码
        $pattern15 = '/^[1-9]\d{5}\d{6}(\d{3})$/';

        if (preg_match($pattern18, $id) || preg_match($pattern15, $id)) {
            return true;
        } else {
            return false;
        }
    }

    public function getAgeByID($id){
        //过了这年的生日才算多了1周岁
        if(empty($id)) return '';
        $date=strtotime(substr($id,6,8));
        //获得出生年月日的时间戳
        $today=strtotime('today');
        //获得今日的时间戳
        $diff=floor(($today-$date)/86400/365);
        //得到两个日期相差的大体年数
        //strtotime加上这个年数后得到那日的时间戳后与今日的时间戳相比
        $age=strtotime(substr($id,6,8).' +'.$diff.'years')>$today?($diff+1):$diff;
        return $age;
    }


    public function workUserList(Request $request)
    {
        $data = $request->all();
        $user_id = $data['user_id'];
        $name = $data['name'];
        $type_work = $data['type_work'];
        $user_info = DB::table('admin_users')->where('id', $user_id)->first();


        if($data['misdeed'] == 1){
            $DB = DB::table('work_user')->where('engineering', $data['engineering'])->where('misdeed',1)->where('status', $data['status'])->where('deleted_at',null);
        }else{
            $DB = DB::table('work_user')->where('engineering', $data['engineering'])->where('misdeed','<>',1)->where('deleted_at',null);
        }

        if(!empty($name)){
            $DB->where('name','like','%'.$name.'%');
        }

        if(!empty($type_work)){
            $DB->where('type_work',$type_work);
        }

        if($user_info->whole == 2){
            $res = $DB->where('uploader',$user_id)->get()->map(function ($value) {return (array)$value;})->toArray();
        }else{
            $res = $DB->get()->map(function ($value) {return (array)$value;})->toArray();
        }

        foreach ($res as $key => $value){
            $res[$key]['photo_portrait'] = env('APP_URL').'uploads'.$value['photo_portrait'];
            $res[$key]['photo_emblem'] = env('APP_URL').'uploads'.$value['photo_emblem'];
            $res[$key]['misdeed'] = DB::table('misdeed')->where('id', $value['misdeed'])->value('name');
        }

        if($user_info->sensitive == 1){
            foreach ($res as $key => $value){
                $res[$key]['photo_portrait'] = '没有查看权限';
                $res[$key]['photo_emblem'] = '没有查看权限';
                $res[$key]['id_card'] = '没有查看权限';
                $res[$key]['bank_number'] = '没有查看权限';
                $res[$key]['mobile'] = '没有查看权限';
            }
        }

        return $this->OkJson($res);
    }



    public function getAppMessage(Request $request){
        $data = $request->all();
        $versionCode = $data['versionCode'];

        $bendi = DB::table('version')->orderBy('id','desc')->first();
        if($versionCode < $bendi->version_code){
            return $this->OkJson($bendi);
        }
        return $this->ErrJson();
    }



    public function DKQsend(Request $request){
        $data = $request->all();
        $name = $data['name'];
        $id_card = $data['id_card'];

        $engineering = $data['engineering'];
        $company = $data['company'];
        $team = $data['team'];
        $type_work = $data['type_work'];
        $mobile = $data['mobile'];
        $bank_deposit = $data['bank_deposit'];
        $bank_number = $data['bank_number'];
        $enter_time =  $data['enter_time'];

        if(empty($name)){return $this->ErrJson('400','姓名不能为空');}
        if(empty($id_card)){return $this->ErrJson('400','身份证号不能为空');}
        if(empty($engineering)){return $this->ErrJson('400','所属工程不能为空');}

        if(empty($company)){return $this->ErrJson('400','公司不能为空');}
        if(empty($team)){return $this->ErrJson('400','队伍不能为空');}
        if(empty($type_work)){return $this->ErrJson('400','工种不能为空');}
        if(empty($mobile)){return $this->ErrJson('400','手机号不能为空');}
        if(empty($bank_deposit)){return $this->ErrJson('400','开户银行不能为空');}
        if(empty($bank_number)){return $this->ErrJson('400','银行卡号不能为空');}
        if(empty($enter_time)){return $this->ErrJson('400','入职时间不能为空');}

        $uploader = $data['uploader'];

        $uploader_id = DB::table('admin_users')->where('mobile',$uploader)->value('id');
        if(empty($uploader_id)){
            return $this->ErrJson('400','上报人手机号错误');
        }
        $engineering_id = DB::table('engineering')->where('engineering_name',$engineering)->where('manager','like','%'.$uploader_id.'%')->value('id');
        if(empty($engineering_id)){
            return $this->ErrJson('400','上报人与工程不符合');
        }

        $base64_photo_portrait = str_replace('data:image/jpeg;base64,', '', $data['photo_portrait']);//获取图片的base64值

        $up_dir = public_path() . "/uploads/photo/";//存放在当前目录的upload文件夹下
        $type = 'png';//文件后缀
        $photo_portrait_name = md5(microtime()) . '.' . $type;//自动生MD5加密文件名
        $new_file = $up_dir . $photo_portrait_name; //拼接文件路径
        file_put_contents($new_file, base64_decode($base64_photo_portrait));//上传文件

        $base64_photo_emblem = str_replace('data:image/jpeg;base64,', '', $data['photo_emblem']);//获取图片的base64值
        $up_dir = public_path() . "/uploads/photo/";//存放在当前目录的upload文件夹下
        $type = 'png';//文件后缀
        $photo_emblem_name = md5(microtime()) . '.' . $type;//自动生MD5加密文件名
        $new_file = $up_dir . $photo_emblem_name; //拼接文件路径
        file_put_contents($new_file, base64_decode($base64_photo_emblem));//上传文件

        $is_exist = DB::table('work_user')->where('deleted_at',null)->where('id_card',$id_card)->first();
        if($is_exist == null){
            DB::table('work_user')->insert(['name'=>$name,
                'id_card'=>$id_card,
                'photo_portrait'=>"/photo/".$photo_portrait_name,
                'photo_emblem'=>"/photo/".$photo_emblem_name,
                'status'=>1,
                'enter_time'=>Carbon::now(),
                'age'=>$this->getAgeByID($id_card),
                'uploader'=>$uploader_id,
                'engineering'=>$engineering,
                'company'=>$company,
                'team'=>$team,
                'type_work'=>$type_work,
                'mobile'=>$mobile,
                'bank_deposit'=>$bank_deposit,
                'bank_number'=>$bank_number,
                'enter_time'=>$enter_time
            ]);

            $history = [];
            $history['name'] = $name;
            $history['id_card'] = $id_card;
            $history['engineering'] = $engineering;
            $history['type'] = 1;
            $history['details'] = '首次入职';
            $history['enter_time'] = $enter_time;
            $history['created_at'] = Carbon::now();
            DB::table('work_user_history')->insert($history);

            return $this->OkJson(200,'新增成功',[]);
        }

        DB::table('work_user')->where('id_card',$id_card)->update(['name'=>$name,
            'id_card'=>$id_card,
            'photo_portrait'=>"/photo/".$photo_portrait_name,
            'photo_emblem'=>"/photo/".$photo_emblem_name,
            'status'=>1,
            'enter_time'=>Carbon::now(),
            'age'=>$this->getAgeByID($id_card),
            'uploader'=>$uploader_id,
            'engineering'=>$engineering,
            'company'=>$company,
            'team'=>$team,
            'type_work'=>$type_work,
            'mobile'=>$mobile,
            'bank_deposit'=>$bank_deposit,
            'bank_number'=>$bank_number,
            'enter_time'=>$enter_time
        ]);
        return $this->OkJson(200,'更新成功',[]);
    }



    public function uploadKIPSGateRecord(Request $request){
        $data = $request->all();
        $mac = $data['mac'];
        $check_time = $data['checkTime'];
        $name = $data['name'];
        $id_card = $data['idCardNo'];

        Log::info('考勤请求：'.$id_card);

//        $hour = Carbon::now()->hour;
//        $minute = Carbon::now()->minute;
//        $second = Carbon::now()->second;
//        $now = $hour.':'.$minute.':'.$second;
        $now = Carbon::now();
        $todayDate = Carbon::today()->toDateString();

        $device = DB::table('device_list')->where('mac',$mac)->first();

        $date_morning = Carbon::parse($todayDate .' '.$device->morning);
        $date_afternoon = Carbon::parse($todayDate .' '.$device->afternoon);

//        var_dump($now->toDateTimeString());
//        var_dump($date_morning->toDateTimeString());
//        var_dump($date_afternoon->toDateTimeString());
//        var_dump($now->greaterThanOrEqualTo($date_afternoon));

        $morning = 0 ;
        $afternoon = 0;
        $hour = date('H');
        $morning_time = "00:00:00";
        $afternoon_time = "00:00:00";
        if($hour < 12){
            $morning_time = $now->toDateTimeString().'||无效时间';
        }
        if($hour >= 12){
            $afternoon_time = $now->toDateTimeString().'||无效时间';
        }
        if ($now->lessThanOrEqualTo($date_morning)) {
            $morning = 1;
            $morning_time = $now->toDateTimeString();
        }
        if ($now->greaterThanOrEqualTo($date_afternoon)) {
            $afternoon = 1;
            $afternoon_time = $now->toDateTimeString();
        }

        $is_today = DB::table('kaoqin_log')->where('id_card',$id_card)->where('today_date',$todayDate)->value('id');
        if(empty($is_today)){
            $res = ['mac'=>$mac,
                    'check_time'=>$check_time,
                    'name'=>$name,'id_card'=>$id_card,
                    'created_at'=>Carbon::now(),
                    'morning'=>$morning,
                    'afternoon'=>$afternoon,
                    'today_date'=>$todayDate,
                    'morning_time'=>$morning_time,
                    'afternoon_time'=>$afternoon_time,
            ];
            DB::table('kaoqin_log')->insert($res);
        }else{
            DB::table('kaoqin_log')->where('id_card',$id_card)->where('today_date',$todayDate)->update(['morning'=>$morning,'afternoon'=>$afternoon,'morning_time'=>$morning_time,'afternoon_time'=>$afternoon_time]);
        }

        return $this->OkJson(200,'打卡成功',[]);
    }

    public function kaoQinStatistics(Request $request){
        $data = $request->all();
        $start = $data['start'];
        $end = $data['end'];
        $engineering_id = $data['engineering_id'];;
        $engineering = DB::table('engineering')->where('id',$engineering_id)->value('engineering_name');


        $res = [];
        if(empty($engineering)){
            $res['subjects'] = [];
            return $res;
        }
//->leftJoin('type_work as tw','tw.name','=','wu.type_work') basic_salary
        $res['subjects'] = DB::table('work_user')->where('deleted_at',null)
            ->where('status',1)
            ->where('engineering',$engineering)
            ->select('name','id_card','type_work','engineering')->get()->map(function ($value) {return (array)$value;})->toArray();


        foreach ($res['subjects'] as $key => $value){
            $basic_salary = DB::table('type_work')->where('name',$value['type_work'])->value('basic_salary');
            $clock_in_day_array = DB::table('kaoqin_log')->whereBetween('created_at',[$start,$end])->where('user_id',$value['id_card'])->get()->map(function ($value) {return (array)$value;})->toArray();

            $day = 0;
            $details = '';
            foreach ($clock_in_day_array as $k => $v){
                $morning = 'X';
                $afternoon = 'X';
                if($v['morning'] == 1){
                    $day += 0.5;
                    $morning = '√';
                }
                if($v['afternoon'] == 1){
                    $day += 0.5;
                    $afternoon = '√';
                }
                $details .= $v['today_date'].'@上午>'.$morning.'@下午>'.$afternoon.'<br><br>';
            }
            $res['subjects'][$key]['details'] = $details;
            $res['subjects'][$key]['clock_in_day'] = $day;
            $res['subjects'][$key]['basic_salary'] = $basic_salary;
        }

        foreach ($res['subjects'] as $key => $value){
            $res['subjects'][$key]['salary'] = $value['clock_in_day'] * $value['basic_salary'];
        }

        return $res;
    }


    public function maoTongFace(Request $request){
        $data = $request->all();
        $sn = $data['sn'];
        $recog_time = $data['logs'][0]['recog_time'];
        $user_id = $data['logs'][0]['user_id'];

        Log::info('考勤请求：'.$user_id);

        $now = Carbon::now();
        $todayDate = Carbon::today()->toDateString();

        $device = DB::table('device_list')->where('sn',$sn)->first();

        $date_morning = Carbon::parse($todayDate .' '.$device->morning);
        $date_afternoon = Carbon::parse($todayDate .' '.$device->afternoon);

        $morning = 0 ;
        $afternoon = 0;
        $hour = date('H');
        $morning_time = "00:00:00";
        $afternoon_time = "00:00:00";
        if($hour < 12){
            $morning_time = $now->toDateTimeString().'||无效时间';
        }
        if($hour >= 12){
            $afternoon_time = $now->toDateTimeString().'||无效时间';
        }
        if ($now->lessThanOrEqualTo($date_morning)) {
            $morning = 1;
            $morning_time = $now->toDateTimeString();
        }
        if ($now->greaterThanOrEqualTo($date_afternoon)) {
            $afternoon = 1;
            $afternoon_time = $now->toDateTimeString();
        }

        $user_name = DB::table('mao_tong_face')->where('user_id',$user_id)->value('name');

        $is_today = DB::table('kaoqin_log')->where('user_id',$user_id)->where('today_date',$todayDate)->value('id');
        if(empty($is_today)){
            $res = ['sn'=>$sn,
                'recog_time'=>$recog_time,
                'user_name'=>$user_name,
                'user_id'=>$user_id,
                'created_at'=>Carbon::now(),
                'morning'=>$morning,
                'afternoon'=>$afternoon,
                'today_date'=>$todayDate,
                'morning_time'=>$morning_time,
                'afternoon_time'=>$afternoon_time,
            ];
            DB::table('kaoqin_log')->insert($res);
        }else{
            DB::table('kaoqin_log')->where('user_id',$user_id)->where('today_date',$todayDate)->update(['morning'=>$morning,'afternoon'=>$afternoon,'morning_time'=>$morning_time,'afternoon_time'=>$afternoon_time]);
        }

        return json_encode(['Result'=>0,'Msg'=>'打卡成功']);
    }

    public function maoTongFaceStatistics(Request $request){
        $data = $request->all();
        $start = $data['start'];
        $end = $data['end'];
        $engineering_id = $data['engineering_id'];
        $engineering = DB::table('engineering')->where('id',$engineering_id)->value('engineering_name');


        $res = [];
        if(empty($engineering)){
            $res['subjects'] = [];
            return $res;
        }
//->leftJoin('type_work as tw','tw.name','=','wu.type_work') basic_salary
        $res['subjects'] = DB::table('work_user')->where('deleted_at',null)
            ->where('status',1)
            ->where('engineering',$engineering)
            ->select('name','id_card','type_work','engineering')->get()->map(function ($value) {return (array)$value;})->toArray();


        foreach ($res['subjects'] as $key => $value){
            $basic_salary = DB::table('type_work')->where('name',$value['type_work'])->value('basic_salary');
            $clock_in_day_array = DB::table('kaoqin_log')->whereBetween('created_at',[$start,$end])->where('user_id',$value['user_id'])->get()->map(function ($value) {return (array)$value;})->toArray();

            $day = 0;
            $details = '';
            foreach ($clock_in_day_array as $k => $v){
                $morning = 'X';
                $afternoon = 'X';
                if($v['morning'] == 1){
                    $day += 0.5;
                    $morning = '√';
                }
                if($v['afternoon'] == 1){
                    $day += 0.5;
                    $afternoon = '√';
                }
                $details .= $v['today_date'].'@上午>'.$morning.'@下午>'.$afternoon.'<br><br>';
            }
            $res['subjects'][$key]['details'] = $details;
            $res['subjects'][$key]['clock_in_day'] = $day;
            $res['subjects'][$key]['basic_salary'] = $basic_salary;
        }

        foreach ($res['subjects'] as $key => $value){
            $res['subjects'][$key]['salary'] = $value['clock_in_day'] * $value['basic_salary'];
        }

        return $res;
    }


    public function maoTongFaceEnter(Request $request){
        $data = $request->all();
        $sn = $data['sn'];
        $user_id = $data['user_id'];
        $name = $data['name'];
//        $validity_period = $data['validity_period'];
//        $card_number = $data['card_number'];
        $photo = $data['photo'];

        $base64_photo_portrait = str_replace('data:image/jpeg;base64,', '', $photo);//获取图片的base64值

        $up_dir = public_path() . "/uploads/mao_tong_face/";//存放在当前目录的upload文件夹下
        $type = 'png';//文件后缀
        $photo_portrait_name = md5(microtime()) . '.' . $type;//自动生MD5加密文件名
        $new_file = $up_dir . $photo_portrait_name; //拼接文件路径
        file_put_contents($new_file, base64_decode($base64_photo_portrait));//上传文件

        $is_exist = DB::table('mao_tong_face')->where('deleted_at',null)->where('user_id',$user_id)->first();
        if($is_exist == null){
            DB::table('mao_tong_face')->insert([
                'sn'=>$sn,
                'user_id'=>$user_id,
                'photo'=>"/mao_tong_face/".$photo_portrait_name,
                'name'=>$name,
                'status'=>1,
                'created_at'=>Carbon::now()
            ]);
            return json_encode(['Result'=>0,'Msg'=>'添加成功']);
        }

        return json_encode(['Result'=>0,'Msg'=>'添加失败']);
    }


    public function ziliaoRevoke(Request $request){
        $id = $_GET['id'];

        $ziliao_content = DB::table('ziliao_content')->where('id',$id)->first();
        $status_info = $ziliao_content->status_info;
        $status_info_array = json_decode($status_info,true);
        foreach ($status_info_array as $key => $value){
            $status_info_array[$key]['status'] = 0;
            $status_info_array[$key]['time'] = '';
        }

        $status_info = json_encode($status_info_array,JSON_UNESCAPED_UNICODE);

        $process = DB::table('ziliao_categories')->where('title',$ziliao_content->categories_id)->value('process');
        $process_array = json_decode($process,true);

        DB::table('ziliao_content')->where('id',$id)->update([
            'step'=>0,
            'role'=>$process_array[0]['role'],
            'process'=>$ziliao_content->uploader,
            'status'=>1,
            'status_info'=>$status_info
        ]);

        return 200;
    }


    public function ziliaoMessage(Request $request){
        $user_id = $_GET['user_id'];

        $ziliao_message_number = DB::table('ziliao_content')->where('process','like',"%".$user_id."%")
                                                                  ->where('status','<=',4)
                                                                  ->where('deleted_at',null)
                                                                  ->count();

        return json_encode(['code' => 200,'re'=>$ziliao_message_number]);
    }

}
